package com.itany.book.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.itany.book.book.service.IBookService;
import com.itany.book.order.service.IRoderService;
import com.itany.book.pojo.Address;
import com.itany.book.pojo.Book;
import com.itany.book.pojo.Order;
import com.itany.book.user.service.IUserService;
import com.itany.book.vo.ResponseResult;
import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.synth.SynthSpinnerUI;
import java.io.Console;
import java.io.PrintWriter;
import java.io.Writer;
import java.security.Principal;
import java.util.*;
import java.util.Map.Entry;

/**
 * Author:yaozhiyuan0117@163.com
 * Time:2019/12/31 15:45
 * Describe:
 * version:1.0
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Reference
    private IRoderService oderService;

    @Reference
    private IUserService userService;

    @Reference
    private IBookService bookService;


    @RequestMapping("/createImg")
    public void  createImg(HttpServletResponse response)throws Exception{
        // 设置响应头和响应内容
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);
        response.setContentType("image/jpeg");
        String qrCode= oderService.getQrCode();

        Map<EncodeHintType,Object> hints = new HashMap<EncodeHintType,Object>();
        hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        BitMatrix bitMatrix = new MultiFormatWriter()
                .encode(qrCode, BarcodeFormat.QR_CODE,200,200,hints);
        MatrixToImageWriter.writeToStream(bitMatrix,"jpeg",response.getOutputStream());
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    @RequestMapping("/paySuccessed")
    @ResponseBody
    public ResponseResult paySuccessed(String no){
        oderService.paySuccess(no);
        return ResponseResult.success();
    }

    @RequestMapping("/paySuccess")
    @ResponseBody
    public String paySuccess()throws Exception{

        // 通过websocket向前台推送消息实现页面的跳转！
        // System.out.println("====================paySuccess=======================");
        // CopyOnWriteArraySet<MySocket> websocket = MySocket.websocket;
        // for(MySocket sk : websocket){
        //     if(sk.getUserId().equals("1")){
        //         sk.getSession().getBasicRemote().sendText("1");
        //     }
        // }

        // 在这里进行支付成功后的业务处理！
        System.out.println("支付成功了，可以进行业务处理!");

        return "success";
    }


    @RequestMapping("findOrderDetails")
    public ResponseResult findOrderDetails(Integer id){
        Order order = oderService.findOrderDetails(id);
        return ResponseResult.success(order);
    }

    @RequestMapping("/submitOrder")
    public ResponseResult submitOrder(Integer addressId,String car, HttpServletRequest request){
        // oderService.submitOrder();
        // System.out.println("--=============----");
        // System.out.println(addressId);
        // System.out.println(car);
        Map cars = JSON.parseObject(car,Map.class);
        Set<String> set = cars.keySet();
        for (String s:set){
            System.out.println(s);
            System.out.println((String)cars.get(s));
        }

        // 获取casClient的参数，用户信息，用户名
        Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        Principal principal = assertion.getPrincipal();
        String username = principal.getName();
        System.out.println("=========="+username);

        // 提交订单！
        String no = oderService.submitOrder(addressId, cars, username);
        return ResponseResult.success(no);
    }

    public static void main(String[] args) {
        // OrderController orderController = new OrderController();
        // orderController.redisTemplate.delete("123_ShoppingCar");
        // System.out.println(orderController.redisTemplate.get);

    }

    /**
     *
     * @param bookid:booid.
     * @return
     */
    @RequestMapping("/joinCar")
    public void joinCar(Integer bookid, HttpServletRequest request, HttpServletResponse response)throws Exception{
        // 获取casClient的参数，用户信息，用户名
        Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        Principal principal = assertion.getPrincipal();
        String username = principal.getName();
        // System.out.println("=========="+username);
        // System.out.println("=========="+bookid);

        // 放入redis中，key为username, 小key为List<Book>的id.
        Book book = bookService.findById(bookid);
        book.setNumberInCar(1);
        String bookStr = JSON.toJSONString(book);
        System.out.println("============bookStr"+ bookStr);
        // redisTemplate.opsForValue().set("ccc","test");
        // 放之前判断是否有这本书？
        Object o = redisTemplate.opsForHash().get(username + "_ShoppingCar", String.valueOf(bookid));
        System.out.println(o);

        if (o ==null){
            redisTemplate.opsForHash().put(username+"_ShoppingCar",String.valueOf(bookid),bookStr);
        //    o不为null， 数量+1
        }else{
            String  bstr= (String) redisTemplate.opsForHash().get(username + "_ShoppingCar", String.valueOf(bookid));
            Book b = JSON.parseObject(bstr, Book.class);
            b.setNumberInCar(b.getNumberInCar()+1);
            redisTemplate.opsForHash().put(username+"_ShoppingCar",String.valueOf(bookid),JSON.toJSONString(b));
        }

        // Map<Object, Object> entries = redisTemplate.opsForHash().entries(username + "_ShoppingCar");
        // for (Entry t : entries.entrySet()){
        //     System.out.println("-------------");
        //     System.out.println(t.getKey());
        //     System.out.println(t.getValue());
        // }

        response.setContentType("text/plain");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        // Map<String,Object> map = new HashMap<String,Object>();
        // map.put("result", "content");
        PrintWriter out = response.getWriter();
        // JSONObject resultJSON = new JSONObject(map);
        String jsonpCallback = request.getParameter("callbacks");
        //
        out.println(jsonpCallback+"({\"flag\":\"successfuly\"})");
        out.flush();
        out.close();

    }

    @RequestMapping("/getCar")
    public ResponseResult getCar(HttpServletRequest request, String car){
        // System.out.println("---car------");
        // System.out.println(car);
        // System.out.println(car.length()); // 2
        // 获取casClient的参数，用户信息，用户名
        Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        Principal principal = assertion.getPrincipal();
        String username = principal.getName();
        // System.out.println("=========="+username);

        /**
         * if length>2:
         *  1. 删除不在car里的。
         *  2.更新在car里的
         *
         *最后取出redis里的内容放入购物车中！
         */
        // newCar有内容，更新redis
        if (car.length()>3){
            Map newCar = JSON.parseObject(car,Map.class);
            System.out.println("这个是用JSON类,指定解析类型，来解析JSON字符串!!!");
            // 直接更新redis中oldCar的数量！
            Set<String> set = newCar.keySet();
            Map<Object, Object> entries = redisTemplate.opsForHash().entries(username + "_ShoppingCar");
            // Set oldCar = entries.keySet();
            for (String o : set){
                String newNumber = (String) newCar.get(o);
                String bookStr = (String) redisTemplate.opsForHash().get(username + "_ShoppingCar",o);
                Book book = JSON.parseObject(bookStr, Book.class);
                // 将数量加到redis里面
                // book.setNumberInCar(book.getNumberInCar()+Integer.parseInt(newNumber));
                book.setNumberInCar(Integer.parseInt(newNumber));
                String newBookStr = JSON.toJSONString(book);
                redisTemplate.opsForHash().put(username + "_ShoppingCar",(String)o,newBookStr);
            }
            /*
            for (Object o: oldCar){
                if (!set.contains((String)o)){
                    redisTemplate.opsForHash().delete(username + "_ShoppingCar",o);
                }else{
                    String newNumber = (String) newCar.get((String)o);
                    String bookStr = (String) redisTemplate.opsForHash().get(username + "_ShoppingCar",o);
                    Book book = JSON.parseObject(bookStr, Book.class);
                    book.setNumberInCar(Integer.parseInt(newNumber));
                    String newBookStr = JSON.toJSONString(book);
                    redisTemplate.opsForHash().put(username + "_ShoppingCar",(String)o,newBookStr);
                }
            }*/
        }
        // 在从redis中取值返回！
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(username + "_ShoppingCar");
        // Collection<Object> books = entries.values();
        // List<Book> b = new ArrayList(books);
        List<Book> res = new ArrayList<>();
        for (Entry t : entries.entrySet()){
            System.out.println("-------------");
            System.out.println(t.getValue());
            Book bb = JSONObject.parseObject((String) t.getValue(), Book.class);
            res.add(bb);
        }
        for (Book bb : res){
            System.out.println(bb);
        }
        return ResponseResult.success(res);
    }

    @RequestMapping("/checkCar")
    public ResponseResult checkCar(HttpServletRequest request, String car){
        // System.out.println("---car------");
        // System.out.println(car);
        // System.out.println(car.length()); // 2
        // 获取casClient的参数，用户信息，用户名
        Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        Principal principal = assertion.getPrincipal();
        String username = principal.getName();
        // System.out.println("=========="+username);
        // newCar有内容，更新redis
        List<Book> res = new ArrayList<>();
        if (car.length()>3){
            Map newCar = JSON.parseObject(car,Map.class);
            // 直接更新redis中oldCar的数量！
            Set<String> set = newCar.keySet();
            Map<Object, Object> entries = redisTemplate.opsForHash().entries(username + "_ShoppingCar");
            // Set oldCar = entries.keySet();
            for (String o : set){
                String newNumber = (String) newCar.get(o);
                String bookStr = (String) redisTemplate.opsForHash().get(username + "_ShoppingCar",o);
                Book book = JSON.parseObject(bookStr, Book.class);
                book.setNumberInCar(Integer.parseInt(newNumber));
                res.add(book);
                String newBookStr = JSON.toJSONString(book);
                redisTemplate.opsForHash().put(username + "_ShoppingCar",(String)o,newBookStr);
            }
        }
        return ResponseResult.success(res);
    }

    @RequestMapping("/getAddress")
    public ResponseResult getAddress(HttpServletRequest request){
        Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        Principal principal = assertion.getPrincipal();
        String username = principal.getName();
        System.out.println("=========="+username);
        System.out.println("获取所有地址！");
        List<Address> addresses = userService.findAllAddress(username);
        for (Address ad: addresses){
            System.out.println(ad);
        }
        return ResponseResult.success(addresses);
    }

    @RequestMapping("/deleteBookInCar")
    public ResponseResult deleteBookInCar(HttpServletRequest request, String id){
        Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        Principal principal = assertion.getPrincipal();
        String username = principal.getName();
        System.out.println("=========="+username);
        redisTemplate.opsForHash().delete(username + "_ShoppingCar",id);
        return ResponseResult.success();
    }

    @RequestMapping("/modifyCar")
    public ResponseResult modifyCar(HttpServletRequest request, String car){
        // 获取casClient的参数，用户信息，用户名
        Assertion assertion = (Assertion) request.getSession().getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
        Principal principal = assertion.getPrincipal();
        String username = principal.getName();
        System.out.println("=========="+username);
        Map<Object, Object> entries = redisTemplate.opsForHash().entries(username + "_ShoppingCar");
        // 清空购物车，重新全部添加
        System.out.println(car);
        //
        return ResponseResult.success();
    }
}
